package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.annotation.Log;
import com.example.demo.annotation.RequestAuthCheck;
import com.example.demo.config.ConstantConfig;
import com.example.demo.entity.*;
import com.example.demo.entity.dto.GiveMenuDto;
import com.example.demo.entity.dto.PageDto;
import com.example.demo.entity.vo.PageVo;
import com.example.demo.entity.vo.ResponseResult;
import com.example.demo.enums.StatusCodeEnum;
import com.example.demo.enums.log.BusinessTypeEnum;
import com.example.demo.enums.log.OperatorTypeEnum;
import com.example.demo.exception.CustomException;
import com.example.demo.service.RoleMenuService;
import com.example.demo.service.RoleService;

import com.example.demo.service.UserRoleService;
import com.example.demo.util.MyExcelUtil;
import com.example.demo.util.NormalUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @description：角色相关接口控制器.
 * @author：lw
 * @create_time：2024/1/8
 **/


@Tag(name="角色接口")
@ApiSupport(order = 2)
@RestController
@RequestMapping(value = "/admin/role")
public class RoleController {
    @Autowired
    RoleService roleService;

    @Autowired
    RoleMenuService roleMenuService;

    @Autowired
    UserRoleService userRoleService;

    private final String menuName="role";

    @Operation(summary = "新增")
    @ApiOperationSupport(order = 1,author = "lw")
    @RequestAuthCheck(menuName = menuName,action = ConstantConfig.add)
    @Log(title = "新增角色",businessType = BusinessTypeEnum.add,operatorType = OperatorTypeEnum.admin_user)
    @PostMapping(value = "/add")
    public ResponseResult<Boolean> add(@RequestBody List<Role> list) {
//        return  ResponseResult.build(roleService.save(role),StatusCodeEnum.add_success);
        return  ResponseResult.build(roleService.saveBatch(list),StatusCodeEnum.add_success);
    }


    @Operation(summary = "删除")
    @ApiOperationSupport(order = 2,author = "lw")
    @RequestAuthCheck(menuName = menuName,action = ConstantConfig.delete)
    @Transactional(rollbackFor = CustomException.class)
    @Log(title = "删除角色",businessType = BusinessTypeEnum.delete,operatorType = OperatorTypeEnum.admin_user)
    @PostMapping(value = "/deleteByIds")
    public ResponseResult<Boolean> deleteByIds(@RequestBody List<Long> ids) {
        //        UpdateWrapper<Role> updateWrapper=new UpdateWrapper<>();
//        updateWrapper.in("id",ids);
//        updateWrapper.set("is_deleted",1);
//        return  ResponseResult.build(userService.update(updateWrapper),StatusCodeEnum.delete_success);
        try{
            ids.forEach(v->{roleMenuService.deleteByRoleId(v);});
            ids.forEach(v->{userRoleService.deleteByRoleId(v);});
        }catch (Exception e){
            throw new CustomException(StatusCodeEnum.delete_fail);
        }
        if(!roleService.removeByIds(ids))   throw new CustomException(StatusCodeEnum.delete_fail);
        return  ResponseResult.build(true,StatusCodeEnum.delete_success);
    }

    @Operation(summary = "更新")
    @ApiOperationSupport(order = 3,author = "lw")
    @RequestAuthCheck(menuName = menuName,action = ConstantConfig.update)
    @Log(title = "更新角色",businessType = BusinessTypeEnum.update,operatorType = OperatorTypeEnum.admin_user)
    @PostMapping(value = "/update")
    public ResponseResult<Boolean> update(@RequestBody List<Role> list) {
//        return  ResponseResult.build(roleService.updateById(role),StatusCodeEnum.update_success);
        return  ResponseResult.build(roleService.updateBatchById(list),StatusCodeEnum.update_success);
    }

    @Operation(summary = "获取详情")
    @ApiOperationSupport(order = 4 ,author = "lw")
    @GetMapping(value = "/detail")
    public ResponseResult<Role> getDetail(Long id) {
        return  ResponseResult.build(roleService.getById(id),StatusCodeEnum.success);
    }

    @Operation(summary = "列表查询")
    @ApiOperationSupport(order = 5,author = "lw")
    @PostMapping(value = "/list")
    public ResponseResult<List<Role>> getList(@RequestBody Role role) {
        return  ResponseResult.build(roleService.getList(role),StatusCodeEnum.query_success);
    }

    @Operation(summary = "分页查询")
    @ApiOperationSupport(order = 6,author = "lw")
    @PostMapping(value = "/page")
    public ResponseResult<PageVo<Role>> getPage(@RequestBody PageDto<Role> pageDto) {
        return  ResponseResult.build(roleService.getPage(pageDto),StatusCodeEnum.query_success);
    }

    @Operation(summary = "导出")
    @ApiOperationSupport(order = 7,author = "lw")
    @RequestAuthCheck(menuName = menuName,action = ConstantConfig.export)
    @PostMapping(value = "/export")
    public void export(@RequestBody PageDto<Role> pageDto, HttpServletResponse response) {
        PageVo<Role> pageVo=roleService.getPage(pageDto);
        MyExcelUtil.export(response,pageVo, NormalUtil.mergeMaps(Role.getExcelCols(), BaseEntity.getExcelCols()),Role.entityTitle);
    }

    @Operation(summary = "导入")
    @ApiOperationSupport(order = 8 ,author = "lw")
    @RequestAuthCheck(menuName = menuName,action = ConstantConfig.Import)
    @PostMapping(value = "/import")
    public ResponseResult<List<Role>>  importList(@RequestPart("file") MultipartFile file){
        List<Role> list=MyExcelUtil.read(file,Role.class);
        return ResponseResult.build(list,StatusCodeEnum.import_success);
    }


    @Operation(summary = "获取角色的菜单id列表")
    @Parameters({
            @Parameter(name = "rid",description = "角色id",required = true,in= ParameterIn.QUERY)
    })
    @ApiOperationSupport(order = 9,author = "lw")
    @GetMapping(value = "/getMenuIds")
    public ResponseResult<List<RoleMenu>> getMenuIds(Long rid) {
        QueryWrapper<RoleMenu> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("rid",rid).eq("is_deleted",0);
        return  ResponseResult.build(roleMenuService.list(queryWrapper),StatusCodeEnum.success);
    }

    @Operation(summary = "分配菜单")
    @ApiOperationSupport(order = 10,author = "lw")
    @RequestAuthCheck(menuName = menuName,action = ConstantConfig.giveAuth)
    @Log(title = "角色授权",businessType = BusinessTypeEnum.giveAuth,operatorType = OperatorTypeEnum.admin_user)
    @PostMapping(value = "/giveMenus")
    public ResponseResult<Boolean> giveMenus(@RequestBody GiveMenuDto giveMenuDto) {
        return  ResponseResult.build(roleService.giveMenus(giveMenuDto),StatusCodeEnum.give_success);
    }
}
